<template>
  <el-upload
    :class="isAvatar ? 'avatar-uploader' : 'upload-demo'"
    action="/user/upload/accessory"
    :on-preview="handleInvoicePhotoPreview"
    :http-request="putUploadAjax"
    :on-remove="handleInvoicePhotoRemove"
    :file-list="state.fileList"
    :limit="limit"
    multiple
    :before-upload="handleInvoicePhotoBefore"
    :on-exceed="handleInvoicePhotoExceed"
    :on-success="handleInvoicePhotoSuccess"
    :before-remove="beforeRemove"
  >
    <template v-if="isAvatar">
      <img v-if="avatarUrl" :src="avatarUrl" alt="图标" class="avatar-image" />
      <!-- <i v-else class="el-icon-plus avatar-uploader-icon"></i>
       -->
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </template>
    <el-button v-else size="small" type="primary">点击上传</el-button>
    <el-dialog v-model="state.dialogVisible">
      <img style="width: 100%" :src="state.dialogImageUrl" alt="" />
    </el-dialog>
  </el-upload>
</template>

<script lang="ts" setup>
import { defineEmits, defineProps, reactive } from 'vue'

import { ElMessage } from 'element-plus'

import { uploadImage } from '@/api/help'

import IBaseObj from '#/index'

const props = defineProps({
  listType: {
    type: String,
    default: 'picture-card',
  },
  limit: {
    type: Number,
    default: null,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  initFiles: {
    type: Array,
    default: () => [],
  },
  tipText: {
    type: String,
    default: '',
  },
  fileType: {
    type: String,
    default: '',
  },
  fileName: {
    type: String,
    default: '',
  },
  fileSize: {
    type: Number,
    default: 5,
  },
  isup: {
    type: Boolean,
    default: false,
  },
  uploadFn: {
    type: Function,
    default: uploadImage,
  },
  previewFn: {
    type: Function,
    default: null,
  },
  isAvatar: {
    type: Boolean,
    default: true,
  },
  avatarUrl: {
    type: String,
    default: '',
  },
})

const state = reactive({
  fileList: [],
  noneBtnDealImg: props.isup,
  dialogImageUrl: '',
  dialogVisible: false,
  successFileList: [],
})

const emits = defineEmits(['change'])

const handleInvoicePhotoBefore = (file: IBaseObj) => {
  const type = file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
  if (props.fileType && props.fileType.indexOf(type) === -1) {
    ElMessage.error(`上传文件的格式不正确，可以上传${props.fileType}`)
    return false
  }
}

const handleInvoicePhotoExceed = () => {
  ElMessage.error(`最多上传${props.limit}个文件`)
}

const putUploadAjax = (param: any) => {
  const formData = new FormData()
  formData.append('file', param.file)
  // 重置上传照片参数
  return new Promise((resolve, reject) => {
    props
      .uploadFn(formData)
      .then((res: any) => {
        console.log('rrrrr', res)
        if (res?.path) {
          param.file.prepareData = res.path
          resolve(param)
        } else {
          ElMessage.error('Retry later please!')
          reject(param)
        }
      })
      .catch((err: any) => {
        console.error(err)
        ElMessage.error('Retry later please!')
        reject()
      })
  })
}

// 展示
const handleInvoicePhotoPreview = (file: any) => {
  if (props.previewFn) {
    props.previewFn(file)
    return
  }
  state.dialogImageUrl = `${import.meta.env.VITE_HOST_URL}/${file.raw.prepareData}`
  state.dialogVisible = true
  console.log('response', file.raw.prepareData)
}

// 上传文件成功
const handleInvoicePhotoSuccess = (response: any, file: any, fileList: any) => {
  console.log(response, file)
  emits('change', processFileList(fileList))
}

// 上传文件删除
const handleInvoicePhotoRemove = (file: any, fileList: any) => {
  console.log(file)
  emits('change', processFileList(fileList))
}

// 格式化回显数据
const processFileList = (fileList: any) => {
  return fileList.map((item: any) => {
    if (item.raw && item.raw.prepareData) {
      return {
        file_name: item.raw.name,
        object_url: item.raw.prepareData,
      }
    }
    return {
      file_name: item.name,
      object_url: item.raw.url,
    }
  })
}

// 文件删除前
const beforeRemove = (fileList: string | any[]) => {
  if (props.isup && fileList.length === 1) {
    ElMessage.warning(`至少保留一个影像文件`)
    return false
  }
}
</script>
<style lang="scss">
.upload-demo {
  display: flex;
  height: 100%;
  padding: 5px;
  overflow-y: auto;
  border-radius: 6px;
  flex-direction: column;

  .el-upload {
    width: 100%;
    text-align: left;

    .fle-upload {
      width: 100%;

      .fle-title {
        color: #fff;
        text-align: left;
        flex: 1;
      }
    }
  }

  .el-upload-list__item-name {
    color: var(--form-color);
  }

  .el-upload-list__item-status-label {
    display: block;
  }
}

.avatar-uploader .el-upload {
  position: relative;
  // width: 100%;
  width: 200px;
  height: 200px;
  overflow: hidden;
  line-height: 200px;
  cursor: pointer;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  width: 100%;
  height: 100%;
  font-size: 28px;
  line-height: 1;
  color: #8c939d;
  text-align: center;
}

.avatar {
  &-image {
    display: block;
    width: 100%;
    height: 100%;
  }
}
</style>
